import {
  Component,
  OnInit,
  AfterViewInit,
  OnDestroy,
  Inject
} from "@angular/core";
import { LocaleService, TranslationService, Language } from "angular-l10n";
import Scrollbar from "smooth-scrollbar";
import { isPlatformBrowser, isPlatformServer } from "@angular/common";
import {
  ISelectSymbolResponse,
  IMu,
  IZi,
  IQuerySymbol
} from "@/trade/store/models/trade";
import * as fromTrade from "@/trade/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { Store, select } from "@ngrx/store";
import { TradeActions } from "@/trade/store/actions";
import { map, filter } from "rxjs/operators";
import { Subscription } from "rxjs";
import { ActivatedRoute } from "@angular/router";
import { Router, NavigationEnd } from "@angular/router";
import { takeUntil, mergeMap } from "rxjs/operators";
import { forkJoin, combineLatest } from "rxjs";
import { FormControl } from "@angular/forms";

import { ReplaySubject } from "rxjs";

@Component({
  selector: "app-panel-symbol",
  templateUrl: "./panel-symbol.component.html",
  styleUrls: ["./panel-symbol.component.scss"]
})
export class PanelSymbolComponent implements OnInit, AfterViewInit, OnDestroy {
  @Language() lang: string;

  onMu: IMu;
  onMu$: FormControl = new FormControl();
  onZi: IZi;
  onZi$: FormControl = new FormControl();
  ziLists$: ReplaySubject<Array<IZi>> = new ReplaySubject<any[]>(1);
  ziLists: Array<IZi> = [];
  muLists: Array<IMu> = [];

  search$: FormControl = new FormControl("");

  trade$ = this.store.pipe(select("trade"));

  symbolLists$ = this.store
    .pipe(select(fromRoot.symbolLists))
    .pipe(filter(symbolLists => !!symbolLists));

  sub$ = {
    symbolListsSub$: null,
    query$: null,
    onMuSub$: null,
    onZiSub$: null,
    searchSub$: null
  };

  search = "";

  querySymbol: IQuerySymbol;

  constructor(
    private store: Store<fromTrade.State>,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    @Inject("UtilsService") private utilsService
  ) {}

  ngAfterViewInit() {
    // Scrollbar.init(document.querySelector("[data-scrollbar]"));
    // Scrollbar.initAll();
  }

  getDefault(): any {
    return {
      onMu: {
        symbol: "BTC",
        lists: []
      },
      onZi: {
        h: "",
        l: "",
        lastPrice: "",
        change: "",
        symbol: "",
        v: "",
        sort: 1,
        isLove: false
      },
      ziLists: [],
      muLists: []
    };
  }

  ngOnInit() {
    this.initDefault();
    this.store.dispatch(
      new TradeActions.SelectSymbol({
        req: undefined
      })
    );
    this.addListen();
  }

  onChangeCoin(e: IMu) {
    this.setOnMu(e);
  }

  addListen() {
    this.sub$.query$ = this.activatedRoute.queryParams.subscribe(query => {
      const { symbol } = query;
      this.querySymbol = this.utilsService.splitQuerySymbol(symbol);

      const def = this.getDefault();

      const mu = Object.assign(def.onMu, {
        symbol: this.querySymbol.mu
      });
    });

    this.sub$.symbolListsSub$ = combineLatest(
      this.symbolLists$,
      this.activatedRoute.queryParams
    ).subscribe(([symbolLists, query]) => {
      this.muLists = symbolLists;

      const { symbol } = query;

      const querySymbol: IQuerySymbol = this.utilsService.splitQuerySymbol(
        symbol
      );

      const def = this.getDefault();

      const zi = Object.assign(def.onZi, {
        symbol: querySymbol.zi
      });

      const mu = Object.assign(def.onMu, {
        symbol: querySymbol.mu
      });

      this.setOnMu(mu);

      this.setOnZi(zi);
    });

    this.sub$.onZiSub$ = this.onZi$.valueChanges.subscribe((zi: IZi) => {
      // console.log(zi, 33333);
    });

    this.sub$.onMuSub$ = this.onMu$.valueChanges.subscribe(e => {
      const timer = setTimeout(() => {
        this.ziLists$.next(
          this.ziLists.slice().filter(d => {
            return d.symbol.indexOf(this.search.toUpperCase()) >= 0;
          })
        );
        clearTimeout(timer);
      }, 0);
    });

    this.sub$.searchSub$ = this.search$.valueChanges.subscribe(e => {
      this.search = e;
      this.ziLists$.next(
        this.ziLists.slice().filter(d => {
          return d.symbol.indexOf(e.toUpperCase()) >= 0;
        })
      );
    });
  }

  initDefault() {
    const def = this.getDefault();

    this.onMu = def.onMu;

    this.onZi = def.onZi;
  }

  resetOnZi() {
    const def = this.getDefault();
    this.onZi = def.onZi;
  }

  onInputSearch(e) {
    const val = e.target.value;
  }

  setOnMu(mu: IMu) {
    // console.log(this.onZi, 99999);
    const muItem = this.getMuItem(mu);
    if (!!muItem) {
      this.resetOnZi();
      this.onMu = muItem;
      this.ziLists = this.getZiLists(mu);
      this.ziLists$.next(this.ziLists.slice());
      this.onMu$.setValue(this.onMu);
    }
  }
  /**
   * 设置选中子币
   *
   * @param {IZi} zi
   * @memberof PanelSymbolComponent
   */
  setOnZi(zi: IZi) {
    const ziLists = this.getZiLists(this.onMu);
    // 这里 是从路由获取的 交易对  只有一个 symbol 字段 所以 要去列表中 找出 这个币 的完整信息
    const ziItem = this.getZiListsItem(ziLists, zi);
    if (!!ziItem) {
      this.onZi = ziItem;
      this.onZi$.setValue(this.onZi);
    }
  }

  /**
   * 跳转到指定子币
   *
   * @param {IZi} zi
   * @memberof PanelSymbolComponent
   */
  toOnZi(zi: IZi) {
    if (!!zi.type && zi.type === "love") {
      this.router.navigate(["/trade/home"], {
        queryParams: { symbol: `${zi.symbol}` }
      });
      return;
    }
    // 路由参数相同时不会触发跳转
    if (
      zi.symbol === this.querySymbol.zi &&
      this.onMu.symbol === this.querySymbol.mu
    ) {
      this.setOnZi(zi);
      return;
    }

    this.router.navigate(["/trade/home"], {
      queryParams: { symbol: `${zi.symbol}_${this.onMu.symbol}` }
    });
  }

  ngOnDestroy() {
    this.utilsService.unsub(this.sub$);
  }

  getMuItem(mu: IMu): IMu {
    const muLists = this.muLists.slice();
    for (const key in muLists) {
      if (muLists.hasOwnProperty(key)) {
        const item = this.muLists[key];
        if (item.symbol === mu.symbol) {
          return item;
        }
      }
    }
    return undefined;
  }

  /**
   * 获取母币的子币列表
   *
   * @param {IMu} mu
   * @returns {Array<IZi>}
   * @memberof PanelSymbolComponent
   */
  getZiLists(mu: IMu): Array<IZi> {
    const muLists = this.muLists.slice();
    for (const key in muLists) {
      if (muLists.hasOwnProperty(key)) {
        const item = muLists[key];
        if (item.symbol === mu.symbol) {
          return item.lists;
        }
      }
    }
    return [];
  }

  getZiListsItem(lists: Array<IZi>, zi: IZi): IZi | undefined {
    for (const item of lists) {
      if (item.symbol === zi.symbol) {
        return item;
      }
    }
    return undefined;
  }
}
